package minesweeper;

import interfaces.Minesweepable;

class OppenedMinesweeper {
	private boolean[][] isOppenedSquare;
	private Minesweepable minesweeper;
	
	boolean isOppenedSquare(int row, int column) {
		return isOppenedSquare[row][column];
	}

	private OppenedMinesweeper(Minesweepable minesweeper, int row, int column) {
		this.minesweeper = minesweeper;
		this.isOppenedSquare = new boolean[row][column];
	}

	static OppenedMinesweeper createOppenedMinesweeper(Minesweepable minesweeper, int row, int column) {
		if(minesweeper != null && row > 0 && column > 0)
			return new OppenedMinesweeper(minesweeper, row, column);
		else
			return null;
	}
	
	void openSquareWithRippleEffect(int row, int column) {
		if(isValidExistaintSquare(row, column)) {
			this.isOppenedSquare[row][column] = true;
			if(minesweeper.getSquare(row, column) == 0)
				rippleSquares(row, column);
		}
	}

	private void rippleSquares(int row, int column) {
		for(int i = -1; i < 2; i++)
			for(int j = -1; j < 2; j++) 
				try {
					if(!this.isOppenedSquare[row + i][column + j]) {
						this.isOppenedSquare[row + i][column + j] = true;
						if(minesweeper.getSquare(row + i, column + j) == 0)
							rippleSquares(row + i, column + j);
					}
				}
				catch(IndexOutOfBoundsException e) {
					//we MUST do nothing -> skip borders/eat exception! (exception ate)
				}
	}

	private boolean isValidExistaintSquare(int row, int column) {
		return row >= 0 && column >= 0 && row < isOppenedSquare.length && column < isOppenedSquare[row].length;
	}

}